package com.ev.apis.controller.scm;

import com.alibaba.fastjson.JSONArray;
import com.ev.apis.model.DsResultResponse;
import com.ev.framework.annotation.EvApiByToken;
import com.ev.framework.config.ConstantForGYL;
import com.ev.framework.utils.EasyPoiUtils;
import com.ev.framework.utils.JSONUtils;
import com.ev.framework.utils.R;
import com.ev.framework.utils.ShiroUtils;
import com.ev.mes.domain.ProductionFeedingDO;
import com.ev.scm.domain.OutsourcingContractDO;
import com.ev.scm.domain.StockInDO;
import com.ev.scm.domain.StockOutDO;
import com.ev.scm.service.OutsourcingContractService;
import com.ev.scm.service.StockInItemService;
import com.ev.scm.service.StockInService;
import com.ev.scm.service.StockOutService;
import com.ev.system.service.RoleService;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author AirOrange
 * @Date 2020-08-17 16:50
 *
 **/

@Api(value="/",tags = "委外退料入库")
@RestController
public class OutsourcingStockInApiController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private OutsourcingContractService outsourcingContractService;
    @Autowired
    private StockOutService stockOutService;
    @Autowired
    private StockInService stockInService;
    @Autowired
    private StockInItemService stockInItemService;

    @EvApiByToken(value = "/apis/scm/outsourcingReturnInStock/saveAndChange", method = RequestMethod.POST, apiTitle = "新增/修改—委外退料入库")
    @ApiOperation("新增/修改—委外退料入库")
    @Transactional(rollbackFor = Exception.class)
    public R addAndEdit(StockInDO stockInDO,
                      @ApiParam(value = "产品/物料明细行[\n" +
                              "{\"materielId\":2,\n" +
                              "\"id\":\"明细主键（修改时必传）\",\n" +
                              "\"batch\":\"批次\",\n" +
                              "\"count\":数量,\n" +
                              "\"unitPrice\":单价,\n" +
                              "\"amount\":金额,\n" +
                              "\"warehouse\":仓库,\n" +
                              "\"warehLocation\":库位,\n" +
                              "\"returnReason\":退货原因,\n" +
                              "\"sourceType\":源单类型,\n" +
                              "\"sourceCode\":\"原单编码\"\n" +
                              "\"sourceId\":\"原单id(追溯用，必传)\"\n" +
                              "}\n" +
                              "]", required = true) @RequestParam(value = "bodyDetail", defaultValue = "") String bodyDetail,
                      @ApiParam(value = "删除的明细id") @RequestParam(value = "itemIds", required = false) Long[] itemIds) {
        // 验证源单数量
        R result=stockInService.checkSourceCountsOfOutSourcingStockOut(bodyDetail,stockInDO.getId());
        if (result == null) {
            return stockInService.addAndChangeInStockType(stockInDO, ConstantForGYL.OUTSOURCE_RETURN, bodyDetail, itemIds);
        }
        return result;

    }

    @EvApiByToken(value = "/apis/scm/outsourcingReturnInStock/audit", method = RequestMethod.POST, apiTitle = "审核--委外退料入库")
    @ApiOperation("审核--委外退料入库")
    @Transactional(rollbackFor = Exception.class)
    public R changeAuditStatus(@ApiParam(value = "委外退料入库主表主键", required = true) @RequestParam(value = "id") Long id) {
        return stockInService.auditAllTypeInStock(id, ShiroUtils.getUserId() ,ConstantForGYL.OUTSOURCE_RETURN);
    }

    @EvApiByToken(value = "/apis/scm/outsourcingReturnInStock/reverseAudit", method = RequestMethod.POST, apiTitle = "反审核--委外退料入库")
    @ApiOperation("反审核--委外退料入库")
    @Transactional(rollbackFor = Exception.class)
    public R reverseAudit(@ApiParam(value = "委外退料入库主表主键", required = true) @RequestParam(value = "id", defaultValue = "") Long id) {
        return stockInService.disAuditInStock(id, ConstantForGYL.OUTSOURCE_RETURN);
    }

    @EvApiByToken(value = "/apis/scm/outsourcingReturnInStock/delete", method = RequestMethod.POST, apiTitle = "删除--委外退料入库")
    @ApiOperation("删除--委外退料入库")
    @Transactional(rollbackFor = Exception.class)
    public R remove(@ApiParam(value = "委外退料入库主表主键", required = true) @RequestParam(value = "ids") Long[] ids) {
        return  stockInService.deleteBatch(ids);
    }

    @EvApiByToken(value = "/apis/scm/outsourcingReturnInStock/list", method = RequestMethod.POST, apiTitle = "生产入库列表/查询/高级查询")
    @ApiOperation("获取委外退料入库列表/查询/高级查询")
    public R otherHeadDetailList(@ApiParam(value = "当前第几页") @RequestParam(value = "pageno", defaultValue = "1", required = false) int pageno,
                                 @ApiParam(value = "一页多少条") @RequestParam(value = "pagesize", defaultValue = "20", required = false) int pagesize,
                                 @ApiParam(value = "单据编号") @RequestParam(value = "inheadCode", defaultValue = "", required = false) String inheadCode,
                                 @ApiParam(value = "供应商（模糊）") @RequestParam(value = "supplierName", defaultValue = "", required = false) String supplierName,
                                 @ApiParam(value = "部门") @RequestParam(value = "deptId", defaultValue = "", required = false) Long deptId,
                                 @ApiParam(value = "物料名（模糊）") @RequestParam(value = "materielName", defaultValue = "", required = false) String materielName,
                                 @ApiParam(value = "审核状态") @RequestParam(value = "auditSign", defaultValue = "", required = false) Long auditSign,
                                 @ApiParam(value = "退货起始时间") @RequestParam(value = "startTime", defaultValue = "", required = false) String startTime,
                                 @ApiParam(value = "退货截止时间") @RequestParam(value = "endTime", defaultValue = "", required = false) String endTime,
                                 @ApiParam(value = "规格型号") @RequestParam(value = "materielSpecification", defaultValue = "", required = false) String materielSpecification,
                                 @ApiParam(value = "制单人id") @RequestParam(value = "createBy", defaultValue = "", required = false) Long createBy,
                                 @ApiParam(value = "制单人名字") @RequestParam(value = "createByName", defaultValue = "", required = false) String createByName,
                                 @ApiParam(value = "制单日期") @RequestParam(value = "createTime", defaultValue = "", required = false) String  createTime) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = new HashMap<>();

        params.put("deptId", deptId);
        params.put("inheadCode", inheadCode);
        params.put("materielName", materielName);
        params.put("supplierName", supplierName);
        params.put("auditSign", auditSign);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("createBy", createBy);
        params.put("createByName", createByName);
        params.put("createTime", createTime);
        params.put("materielSpecification", materielSpecification);
        params.put("storageType", ConstantForGYL.OUTSOURCE_RETURN);
        params.put("offset", (pageno - 1) * pagesize);
        params.put("limit", pagesize);

        params.put("isSupplier", 1);
        params.putAll(roleService.getDataPermission(2));

        Map<String, Object> totalForMap = stockInService.countForMap(params);
        List<Map<String, Object>> detailList = stockInService.listForMap(params);

        if (!detailList.isEmpty()) {
            List<String> sourceCodes = detailList.stream().filter(e -> e.containsKey("sourceCode")).map(e -> e.get("sourceCode").toString()).collect(Collectors.toList());
            if (sourceCodes.size() > 0) {
                Map<String,Object> param = Maps.newHashMap();
                param.put("codes",sourceCodes);
                List<StockOutDO> list = stockOutService.list(param);
                Map<String, Long> codeToId = list.stream().collect(Collectors.toMap(StockOutDO::getOutCode, StockOutDO::getId));
                detailList.forEach(e->{
                    String sourceCode = e.getOrDefault("sourceCode", "").toString();
                    e.put("queryId",codeToId.get(sourceCode));
                });
            }


            int total = Integer.parseInt(totalForMap.get("count").toString());
            result.put("data", new DsResultResponse(pageno, pagesize, total, detailList));
            result.put("totalCount", totalForMap.get("toatalCount"));
            result.put("totalAmount", totalForMap.get("toatalAmount"));
        }
        return R.ok(result);
    }


    @EvApiByToken(value = "/apis/scm/outsourcingReturnInStock/getDetail", method = RequestMethod.POST, apiTitle = "详情--委外退料入库")
    @ApiOperation("获取详情--委外退料入库")
    public R getDetail(@ApiParam(value = "委外退料入库主表主键", required = true) @RequestParam(value = "id") Long id) {

        Map<String, Object> params = Maps.newHashMapWithExpectedSize(1);
        params.put("id", id);
        Map<String, Object> detailOfHead = stockInService.deatilOfhead(params);
        List<Map<String, Object>> detailOfBody = stockInItemService.deatilOfBody(params);
        Map<String, Object> result = new HashMap<>();
        if (Objects.nonNull(detailOfHead)) {
            Map<String, Object> map = Maps.newHashMap();
            map.put("detailOfHead", detailOfHead);
            map.put("detailOfBody", detailOfBody);
            result.put("data", map);
        }
        return R.ok(result);
    }


    @ResponseBody
    @EvApiByToken(value = "/apis/scm/exportExcel/outsourcingReturnInStockGetOut", method = RequestMethod.GET, apiTitle = "导出委外退料")
    @ApiOperation("导出委外退料")
    public void exportExcel(
            @ApiParam(value = "单据编号") @RequestParam(value = "inheadCode", defaultValue = "", required = false) String inHeadCode,
            @ApiParam(value = "供应商（模糊）") @RequestParam(value = "supplierName", defaultValue = "", required = false) String supplierName,
            @ApiParam(value = "部门") @RequestParam(value = "deptId", defaultValue = "", required = false) Long deptId,
            @ApiParam(value = "物料名（模糊）") @RequestParam(value = "materielName", defaultValue = "", required = false) String materielName,
            @ApiParam(value = "审核状态") @RequestParam(value = "auditSign", defaultValue = "", required = false) Long auditSign,
            @ApiParam(value = "退货起始时间") @RequestParam(value = "startTime", defaultValue = "", required = false) String startTime,
            @ApiParam(value = "退货截止时间") @RequestParam(value = "endTime", defaultValue = "", required = false) String endTime,
            @ApiParam(value = "规格型号") @RequestParam(value = "materielSpecification", defaultValue = "", required = false) String materielSpecification,
            @ApiParam(value = "制单人id") @RequestParam(value = "createBy", defaultValue = "", required = false) Long createBy,
            @ApiParam(value = "制单人名字") @RequestParam(value = "createByName", defaultValue = "", required = false) String createByName,
            @ApiParam(value = "制单日期") @RequestParam(value = "createTime", defaultValue = "", required = false) String  createTime,
            HttpServletRequest request,
            HttpServletResponse response,
            ModelMap modelMap) {

        Map<String, Object> params = new HashMap<>();

        params.put("deptId", deptId);
        params.put("inheadCode", inHeadCode);
        params.put("supplierName", supplierName);
        params.put("materielName", materielName);
        params.put("auditSign", auditSign);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("materielSpecification", materielSpecification);
        params.put("createBy", createBy);
        params.put("createByName", createByName);
        params.put("createTime", createTime);
        params.put("storageType", ConstantForGYL.OUTSOURCE_RETURN);

        params.put("isSupplier", 1);
        params.putAll(roleService.getDataPermission(2));
        List<Map<String, Object>> list =  stockInService.listForMap(params);
        JSONArray format = JSONUtils.format(list);
        String chineseName = "委外退料";
        String fileName = "poi/scm_outsourcing_return_in_stock.xlsx";
        EasyPoiUtils.processingExport(request,response,modelMap,fileName,format,chineseName);
    }



}
